package com.hancx.controller;

import com.hancx.dao.UserRepository;
import com.hancx.entity.UserInfo;
import org.apache.catalina.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Optional;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserRepository userRepository;

    @PostMapping(value = "/create")
    @ResponseBody
    public UserInfo create() throws ParseException {
        UserInfo user = new UserInfo();
        user.setUserName("admin");
        user.setRealName("admin");

        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1990-01-02"));
        user.setEmail("hancx_self@163.com");
        user.setPhone("18500830161");
        user.setPassword("123456");
        user.setUseFlag('Y');
        user.setCreateTime(new Date());
        user.setCreateOper(1);

        userRepository.save(user);
        return  user;
    }

    @GetMapping(value = "/list")
    @ResponseBody
    public Page<UserInfo> list(@RequestParam(value = "page", defaultValue = "1") Integer page,  //从第0页开始查
                               @RequestParam(value = "limit", defaultValue = "15") Integer limit,  //每页展示几个
                               @RequestParam(value = "sorts", defaultValue = "uid") String sorts){  //排序的字段

        Sort sort = new Sort(Sort.Direction.ASC, sorts);
        Pageable pageable = new PageRequest(page - 1, limit, sort);
        Page<UserInfo> pages = userRepository.findAll(pageable);
        return pages;
    }

    @PostMapping(value = "/update")
    @ResponseBody
    public String update(UserInfo userinfo){
        userRepository.save(userinfo);
        return "success";
    }

    @PostMapping(value = "/del")
    @ResponseBody
    public String delete(@RequestParam(name = "uids[]") Integer uids[]){
        for(int i = 0; i < uids.length; i++){
            userRepository.deleteById(uids[i]);
        }
        return "success";
    }

}
